#include "cp_queue.hpp"
#include <iostream>
#include <pthread.h>
#include <ctime>
#include <unistd.h>
using namespace std;
// cp-生产消费者模型  遵循 321 原则
//  3 -> 三种关系（cc，cp，pp） 2->两种角色 1->一个交易场所
struct ThreadDate
{
    string threadname;
    cp_queue<int> *rq;
};
void *Consumer(void *args)
{
    ThreadDate *td = static_cast<ThreadDate *>(args);
    cp_queue<int> *rq = td->rq;
    string name = td->threadname;
    // 消费数据
    while (true)
    {
        // sleep(1);
        int data = 0;
        rq->pop(&data);
        cout << "Consumer get data: " << data << ",who:" << name << endl;
    }
}

void *Productor(void *args)
{

    ThreadDate *td = static_cast<ThreadDate *>(args);
    cp_queue<int> *rq = td->rq;
    string name = td->threadname;

    while (true)
    {
        // 获得数据
        int data = rand() % 10 + 1;
        // 生产数据
        rq->push(data);
        cout << "Productor date done: " << data << ",who:" << name << endl;
        }
}
int main()
{
    srand(time(NULL));
    pthread_t c[5], p[5];
    cp_queue<int> *rq = new cp_queue<int>(20);

    for (int i = 0; i < 5; i++)
    {
        ThreadDate *td = new ThreadDate();
        td->rq = rq;
        td->threadname = "C_thread-" + to_string(i);
        pthread_create(c + i, NULL, Consumer, td);
    }
    for (int i = 0; i < 5; i++)
    {
        ThreadDate *td = new ThreadDate();
        td->rq = rq;
        td->threadname = "P_thread-" + to_string(i);
        pthread_create(p + i, NULL, Productor, td);
    }
    for (int i = 0; i < 5; i++)
    {
        pthread_join(c[i], NULL);
    }
    for (int i = 0; i < 5; i++)
    {

        pthread_join(p[i], NULL);
    }

    return 0;
}